import { GlobalData, ILotteryGrade } from "../../../Script/Common/GlobalData";
import GameUtil from "../../Util/GameUtil";

const { ccclass, property } = cc._decorator;

@ccclass
export default class Eraser extends cc.Component {

    @property({ type: cc.Node, tooltip: "刮刮乐遮罩层" })
    protected myMask: cc.Node = null;

    @property({ type: cc.Node, tooltip: "刮刮乐奖励层" })
    protected items: cc.Node = null;

    @property({
        displayName: "刮卡路径大小",
        min: 20
    })
    protected size: number = 40;

    @property({ tooltip: "分片后阈值:\n结果判断会依赖此值", type: cc.Integer })
    protected value = 40;

    @property({ type: cc.Node, tooltip: "再来一次按钮" })
    protected btnRestart: cc.Node = null;
    @property({ type: cc.Label, tooltip: "再来一次按钮金额" })
    protected labRestart: cc.Label = null;


    protected positionProgress: Boolean[] = null;
    protected positions: cc.Vec2[] = [];

    protected isGameEnd: boolean = false;

    protected data: { p: number, grades: ILotteryGrade[] } = null;
    protected totalArr: number[] = [];
    protected grade: ILotteryGrade = null;

    protected onLoad() { }

    public restart() {
        this.isGameEnd = false;
        this.myMask.active = false;
        this.myMask.active = true;

        this.data = GlobalData.deepCopyLotteryData();
        this.totalArr = this.getRewardsByChance();
        this.grade = this.getRewardGrade();

        // 再来一次按钮金额
        const config = GlobalData.getLotteryConfig(GlobalData.lotteryType);
        if (!config.isVideo) {
            this.labRestart.string = `${GameUtil.changeUnit(config.needMoney)}`;
        }

        this.btnRestart.active = false;
        
        // console.log('this.totalArr:', this.totalArr);
    }

    protected onEnable() {
        this.node.on(cc.Node.EventType.TOUCH_START, this.onTouchBegin, this);
        this.node.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMoved, this);
        this.node.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.on(cc.Node.EventType.TOUCH_CANCEL, this.onTouchCancel, this);
    }

    protected onDisable() {
        this.node.off(cc.Node.EventType.TOUCH_START, this.onTouchBegin, this);
        this.node.off(cc.Node.EventType.TOUCH_MOVE, this.onTouchMoved, this);
        this.node.off(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.off(cc.Node.EventType.TOUCH_CANCEL, this.onTouchCancel, this);
    }

    protected random(arr): number {
        if (Array.isArray(arr)) {
            const index = Math.floor(Math.random() * arr.length);
            const value = arr[index];
            return value;
        } else {
            const index = Math.floor(Math.random() * arr);
            return index;
        }
    }

    protected getValueByWeight() {
        const datas = [
            { p: 100, value: 0.1 },
            { p: 80, value: 0.5 },
            { p: 50, value: 1 },
            { p: 20, value: 2 },
            { p: 10, value: 5 },
            { p: 5, value: 10 },
            { p: 5, value: 20 },
            { p: 3, value: 50 },
            { p: 1, value: 100 },
        ];
        let p = Math.random();
        let temp = 0;
        let total = 0;
        datas.forEach((o) => {
            total += o.p;
        });

        for (let i = 0; i < datas.length; i++) {
            temp += datas[i].p / total;
            if (temp >= p) {
                return datas[i].value;
            }
        }
    }

    protected getRewardsByChance() {
        const total: number[] = [];
        this.data.grades.forEach((o, i) => {
            o.values.forEach((o1, i1) => {
                total.push(o1 * o.ratio); // 乘倍数
            });
        });
        return total;
    }

    protected getRewardGrade() {
        let grade = this.data.grades;
        let p = Math.random();
        let temp = 0;
        let total = 0;
        grade.forEach((o) => {
            total += o.p;
        });
        for (let i = 0; i < grade.length; i++) {
            temp += grade[i].p / total;
            if (temp >= p) {
                return grade[i];
            }
        }
    }

    protected onTouchBegin(event) {
        if (this.isGameEnd) return;

        var point = event.touch.getLocation();
        point = this.node.convertToNodeSpaceAR(point);
        this.addCircle(point);
    }

    protected onTouchMoved(event) {
        if (this.isGameEnd) return;

        var point = event.touch.getLocation();
        point = this.node.convertToNodeSpaceAR(point);
        this.addCircle(point);
    }

    protected onTouchEnd(event) {
        if (this.isGameEnd) return;

        var point = event.touch.getLocation();
        point = this.node.convertToNodeSpaceAR(point);
        this.addCircle(point);
        this.checkProgress();
    }

    protected onTouchCancel(event) {
        if (this.isGameEnd) return;
        this.checkProgress();
    }

    /**绘制函数*/
    protected graphics: cc.Graphics;
    protected addCircle(point) {
        if (this.isGameEnd) return;

        // console.log("point---", point);
        this.graphics = this.myMask.getComponent(cc.Mask)['_graphics'];
        this.checkPoint(point);
        this.graphics.circle(point.x - this.myMask.x, point.y - this.myMask.y, this.size);
        this.graphics.fill();
    }

    protected checkPoint(point: cc.Vec2) {
        if (this.isGameEnd) return;

        for (let i = 0; i < this.positions.length; i++) {
            let p = cc.v2(this.positions[i].x + this.myMask.x, this.positions[i].y + this.myMask.y);
            // 此点在关键点附近
            if (p.x + this.value > point.x && p.x - this.value < point.x && p.y + this.value > point.y && p.y - this.value < point.y) {
                this.positionProgress[i] = true;
            }
        }
        // console.log("p---", this.positionProgress);
    }

    protected checkProgress() {
        if (this.isGameEnd) return;

        this.isGameEnd = this.positionProgress.filter((value) => { return value; }).length === this.positions.length;
        console.log("this.isGameEnd:", this.isGameEnd);
        if (this.isGameEnd) {
            this.myMask.active = false;
            this.checkReward();
        }
    }

    protected checkReward() {
        this.btnRestart.active = true;
    }
}